package com.example.zjsr.controller;
import com.example.zjsr.common.Key;
import com.example.zjsr.common.ServerResponse;
import com.example.zjsr.pojo.UserVo;
import com.example.zjsr.util.*;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;


/**
 * 用户模块
 */
@Controller
@RequestMapping("/user")
@CrossOrigin //todo 跨域问题
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);


    /**
     * 解析ticket,返回用户信息
     * @param ticket
     * @return
     */
    @RequestMapping(value = "/ilab/login",method = RequestMethod.GET)
    @ResponseBody
    public ServerResponse<Object> Testlogin(String ticket){
        try {
            // 解析token获取包含username的json字符串
            String appid=String.valueOf(Key.issuerId);
            String AesKey=Key.AesKey;
            String Ticket= URLDecoder.decode(ticket,"UTF-8");
            String SIGNATURE=CipherUtil.generatePassword(Ticket+appid+AesKey);
            //测试地址和正式地址 http://202.205.145.156:8017->http://www.ilab-x.com
            System.out.println("http://www.ilab-x.com/open/api/v2/token?ticket="+ticket+"&appid="+appid+"&signature="+SIGNATURE);
            String code = HttpUtil.loadJSON("http://www.ilab-x.com/open/api/v2/token?ticket="+ticket+"&appid="+appid+"&signature="+SIGNATURE);
            // todo ilabJson乱码了！ 2019年10月12日09:39:58
            JSONObject o = JSONObject.fromObject(code);
            logger.info("返回的数据{}",o);
            Integer codeCheck=o.getInt("code");
            logger.info("codeCheck={}",codeCheck);
            if(codeCheck!=0){
                //todo codeCheck是ilab返回的数据信息反馈,案例：({"code":0, "access_token":"4hCwDHmIAf8Bj+TVe7GBVUaLOY0rJiDyWtCmNhixIsBJnZLiAPhmYc0vBLr592Zj","create_time":1598230461000,"create_time_display":"2020-08-24 08:54:21","expires_time":1598237661236,"expires_time_display":"2020-08-24 10:54:21", "un":"username", "dis":"用户姓名"})
                //todo 判断用户ilab返回的ticket是否继续有效(如果不是为0的话，那就是失效；0为ticket有效)
                return ServerResponse.createByErrorMsg("解析失败,请重新通过ilab登录");
            }
            return ServerResponse.createBySuccess(o);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ServerResponse.createByErrorMsg("解析失败,请重新通过ilab登录");
    }
}
